import {create, deleteById, findOne, list, modify} from '@/services/canal-api';
import {PlusOutlined} from '@ant-design/icons';
import {enumInversion,enumInKey} from '@/utils/calculateUtil';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';
import {HAMode,IndexMode,MetaMode,RunMode,StorageMode,BatchMode} from '@/services/ant-design-pro/enums'

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Pipeline) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Pipeline) => {
  const hide = message.loading('更新中');
  try {
    const res = await modify(fields);
    hide();

    if (res) {
      message.success('更新成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};


const Canal: React.FC = () => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Canal>();
  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.Canal) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  const commonColumns: ProColumns<API.Canal>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch:true,
    },
    {
      title: 'Canal名字',
      dataIndex: 'name'
    },
    {
      title: '数据源类型',
      dataIndex: ['canalParameter', 'sourcingType'],
      hideInSearch: true,
    },
    {
      title: '编码',
      dataIndex: ['canalParameter', 'connectionCharset'],
      hideInSearch: true,
    },
    {
      title: '链接配置',
      dataIndex: ['url'],
      hideInSearch: true,
    },
  ]

  const descriptionColumns: ProColumns<API.Canal>[] = [
    ...commonColumns,
    {
      title: '运行状态',
      dataIndex: ['status'],
    },
    {
      title: '运行模式',
      dataIndex: ['canalParameter', 'runMode'],
      renderText:(value) => value? enumInversion(RunMode)[value]: '-',
    },
    {
      title: 'Zookeeper集群',
      dataIndex: ['canalParameter','zkClusters'],
      renderText: (value: Array<string>) => value.join(','),
    },
    {
      title: '数据库地址',
      dataIndex: ['canalParameter', 'groupDbAddresses'],
    },
    {
      title: '数据库帐号',
      dataIndex: ['canalParameter', 'dbUsername'],
    },
    {
      title: '本地localBinlog目录',
      dataIndex: ['canalParameter', 'localBinlogDirectory'],
    },
    {
      title: '是否启用gtid位点',
      dataIndex: ['canalParameter', 'gtidEnable'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '位点信息',
      dataIndex: ['canalParameter', 'positions'],
    },
    {
      title: '是否开启表结构TSDB',
      dataIndex: ['canalParameter', 'tsdbEnable'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: 'rds accesskey',
      dataIndex: ['canalParameter', 'rdsAccesskey'],
    },
    {
      title: 'rds secretkey',
      dataIndex: ['canalParameter', 'rdsSecretkey'],
    },
    {
      title: 'rds instanceId',
      dataIndex: ['canalParameter', 'rdsInstance'],
    },
    {
      title: '存储机制',
      dataIndex: ['canalParameter', 'storageMode'],
      renderText:(value) => value? enumInversion(StorageMode)[value]: '-',
    },
    {
      title: '内存存储batch获取模式',
      dataIndex: ['canalParameter', 'storageBatchMode'],
      renderText:(value) =>  enumInKey(BatchMode,value),
    },
    {
      title: '内存存储buffer记录数',
      dataIndex: ['canalParameter', 'memoryStorageBufferSize'],
    },
    {
      title: '内存存储buffer记录单元大小',
      dataIndex: ['canalParameter', 'memoryStorageBufferMemUnit'],
    },
    {
      title: '文件存储的目录位置',
      dataIndex: ['canalParameter', 'fileStorageDirectory'],
    },
    {
      title: '文件存储store记录数',
      dataIndex: ['canalParameter', 'fileStorageStoreCount'],
    },
    {
      title: 'store文件个数',
      dataIndex: ['canalParameter', 'fileStorageRollverCount'],
    },
    {
      title: 'store存储占disk百分比',
      dataIndex: ['canalParameter', 'fileStoragePercentThresold'],
    },
    {
      title: 'HA机制',
      dataIndex: ['canalParameter', 'haMode'],
      renderText:(value) => value? enumInversion(HAMode)[value]: '-',
    },
    {
      title: 'media group key',
      dataIndex: ['canalParameter', 'mediaGroup'],
    },
    {
      title: '是否开启心跳',
      dataIndex: ['canalParameter', 'detectingEnable'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '心跳sql',
      dataIndex: ['canalParameter', 'detectingSQL'],
    },
    {
      title: '心跳检测频率',
      dataIndex: ['canalParameter', 'detectingIntervalInSeconds'],
    },
    {
      title: '心跳超时时间（秒）',
      dataIndex: ['canalParameter', 'detectingTimeoutThresholdInSeconds'],
    },
    {
      title: '心跳检查重试次数',
      dataIndex: ['canalParameter', 'detectingRetryTimes'],
    },
    {
      title: '是否启用心跳HA',
      dataIndex: ['canalParameter', 'heartbeatHaEnable'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: 'meta机制',
      dataIndex: ['canalParameter', 'metaMode'],
      renderText:(value) =>  enumInKey(MetaMode,value),
    },
    {
      title: '索引机制',
      dataIndex: ['canalParameter', 'indexMode'],
      renderText:(value) =>  enumInKey(IndexMode,value),
    },
    {
      title: '服务端口',
      dataIndex: ['canalParameter', 'port'],
    },
    {
      title: '默认连接超时（秒）',
      dataIndex: ['canalParameter', 'defaultConnectionTimeoutInSeconds'],
    },
    {
      title: '接收BufferSize',
      dataIndex: ['canalParameter', 'receiveBufferSize'],
    },
    {
      title: '发送BufferSize',
      dataIndex: ['canalParameter', 'sendBufferSize'],
    },
    {
      title: '切换回退时间（秒）',
      dataIndex: ['canalParameter', 'fallbackIntervalInSeconds'],
    },
    {
      title: '过滤表达式',
      dataIndex: ['canalParameter', 'blackFilter'],
    },
    {
      title: '描述信息',
      dataIndex: ['desc'],
    },
  ];

  const columns: ProColumns<API.SeniorCanal>[] = [
    ...commonColumns,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (<>
        <Space>
          <a
            key="detail"
            onClick={() => {
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>

          <a
            key="edit"
            onClick={() => {
              handleCreateOrUpdateModalOpen(true);
              handleIsCreate(false);
              setCurrentRow(record);
            }}
          >
            编辑
          </a>
          {!record?.used && (
            <>
              <a
                type='button'
                key="delete"
                onClick={() => {
                  Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                }}
              >删除
              </a>
            </>
          )}
        </Space></>)

    }
  ];

  return (
    <PageContainer>
      <ProTable<API.Canal, API.PageParams>
        headerTitle='Canal列表'
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <CreateOrUpdateForm
        onSubmit={async (value) => {
          let success;
          if (currentRow?.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleCreateOrUpdateModalOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
            return true;
          }
          return false;
        }}
        title={isCreate ? '新建' : '编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={currentRow}
      />

      <Drawer
        width={800}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.Canal>
            column={2}
            title={currentRow?.name}
            request={async () => findOne(currentRow?.id)}
            params={{
              id: currentRow?.id,
            }}
            columns={descriptionColumns as ProDescriptionsItemProps<API.Canal>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Canal;
